package com.ruoyi.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.domain.*;
import com.ruoyi.service.IExExperimentMainService;
import com.ruoyi.service.IExExperimentSideService;
import com.ruoyi.service.IExExperimentSupplementaryService;
import com.ruoyi.service.IExTemplateMainService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;


/**
 * 学生实验主Controller
 * 
 * @author ruoyi
 * @date 2024-08-24
 */
@RestController
@RequestMapping("/system/studmain")
public class ExExperimentMainController extends BaseController
{
    @Autowired
    private IExExperimentMainService exExperimentMainService;

    @Autowired
    private IExExperimentSideService exExperimentSideService;

    @Autowired
    private IExExperimentSupplementaryService exExperimentSupplementaryService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private IExTemplateMainService exTemplateMainService;

    /**
     * 查询学生实验主列表
     */
    @GetMapping("/list")
    public TableDataInfo list(ExExperimentMain exExperimentMain)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = userService.selectUserById(loginUser.getUserId());
        exExperimentMain.setCreatorId(sysUser.getUserId().toString());
        startPage();
        List<ExExperimentMain> list = exExperimentMainService.selectExExperimentMainList(exExperimentMain);
        for (ExExperimentMain experimentMain : list) {
            ExExperimentSide exTemplateSide = new ExExperimentSide();
            exTemplateSide.setMainTableId(experimentMain.getId());
            List<ExExperimentSide> exTemplateSides = exExperimentSideService.selectExExperimentSideList(exTemplateSide);
            experimentMain.setSideTables(exTemplateSides);
            ExExperimentSupplementary supplementary = new ExExperimentSupplementary();
            supplementary.setExperimentMainId(experimentMain.getId());
            List<ExExperimentSupplementary> exExperimentSupplementaries = exExperimentSupplementaryService.selectExExperimentSupplementaryList(supplementary);
            experimentMain.setSupplementaries(exExperimentSupplementaries);
        }
        return getDataTable(list);
    }

    /**
     * 查询实验记录列表
     */
    @GetMapping("/listStastic")
    public TableDataInfo listStastic(ExExperimentMain exExperimentMain)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = userService.selectUserById(loginUser.getUserId());
        exExperimentMain.setLoginId(sysUser.getUserId().toString());
        List<SysRole> sysRoles = roleService.selectRolesByUserId(sysUser.getUserId());
        int flag = 0;
        for (SysRole sysRole : sysRoles) {
            if (sysRole.isFlag() == true && (sysRole.getRoleName().indexOf("管理员") > -1 || sysRole.getRoleName().indexOf("PI") > -1)){
                flag = 1;
            }
        }
        List<ExExperimentMain> list = new ArrayList<>();
        startPage();
        if (flag == 1){
            list = exExperimentMainService.selectExExperimentMainList(exExperimentMain);
        }else {
            list = exExperimentMainService.selectExExperimentMainListStastic(exExperimentMain);
        }

        for (ExExperimentMain experimentMain : list) {
            ExExperimentSide exTemplateSide = new ExExperimentSide();
            exTemplateSide.setMainTableId(experimentMain.getId());
            List<ExExperimentSide> exTemplateSides = exExperimentSideService.selectExExperimentSideList(exTemplateSide);
            experimentMain.setSideTables(exTemplateSides);
            ExExperimentSupplementary supplementary = new ExExperimentSupplementary();
            supplementary.setExperimentMainId(experimentMain.getId());
            List<ExExperimentSupplementary> exExperimentSupplementaries = exExperimentSupplementaryService.selectExExperimentSupplementaryList(supplementary);
            experimentMain.setSupplementaries(exExperimentSupplementaries);
        }
        return getDataTable(list);
    }

    /**
     * 导出学生实验主列表
     */
    @Log(title = "学生实验主表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ExExperimentMain exExperimentMain)
    {
        List<ExExperimentMain> list = exExperimentMainService.selectExExperimentMainList(exExperimentMain);
        ExcelUtil<ExExperimentMain> util = new ExcelUtil<ExExperimentMain>(ExExperimentMain.class);
        util.exportExcel(response, list, "学生实验主数据");
    }

    /**
     * 获取学生实验主详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        ExExperimentMain experimentMain = exExperimentMainService.selectExExperimentMainById(id);
        ExExperimentSide side = new ExExperimentSide();
        side.setMainTableId(id);
        List<ExExperimentSide> exExperimentSides = exExperimentSideService.selectExExperimentSideList(side);
        experimentMain.setSideTables(exExperimentSides);
//        添加补充内容
        ExExperimentSupplementary supplementary = new ExExperimentSupplementary();
        supplementary.setExperimentMainId(experimentMain.getId());
        List<ExExperimentSupplementary> exExperimentSupplementaries = exExperimentSupplementaryService.selectExExperimentSupplementaryList(supplementary);
        experimentMain.setSupplementaries(exExperimentSupplementaries);
        return success(experimentMain);
    }

    /**
     * 新增学生实验主
     */
    @Log(title = "学生实验主表", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ExExperimentMain exExperimentMain)
    {
        //增加模板调用次数
        String tempId = exExperimentMain.getTempId();
        if (tempId!=null){
            if (!tempId.equals("")){
                ExTemplateMain exTemplateMain = exTemplateMainService.selectExTemplateMainById(tempId);
                String callNum1 = exTemplateMain.getCallNum();
                if (callNum1!=null){
                    if (!callNum1.equals("")){
                        int callNum = Integer.parseInt(callNum1);
                        exTemplateMain.setCallNum(String.valueOf(callNum + 1));
                    }else {
                        exTemplateMain.setCallNum("1");
                    }
                }else {
                    exTemplateMain.setCallNum("1");
                }
                exTemplateMainService.updateExTemplateMain(exTemplateMain);
            }
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = userService.selectUserById(loginUser.getUserId());
        String mainTbaleId = UUID.randomUUID().toString();
        List<ExExperimentSide> sideTables = exExperimentMain.getSideTables();
        exExperimentMain.setId(mainTbaleId);
        exExperimentMain.setCreatorId(sysUser.getUserId().toString());
        exExperimentMain.setCreatorName(sysUser.getNickName());
        exExperimentMain.setExperimentStatus("0");

        int index = 1;
        for (ExExperimentSide sideTable : sideTables) {
            sideTable.setMainTableId(mainTbaleId);
            sideTable.setStepNum(String.valueOf(index));
            sideTable.setStepStatus("1");
            exExperimentSideService.insertExExperimentSide(sideTable);
            index++;
        }
        return toAjax(exExperimentMainService.insertExExperimentMain(exExperimentMain));
    }

    /**
     * 检验是否还有步骤没完成
     */
    @PostMapping("/isHaveNotComp")
    public AjaxResult isHaveNotComp(@RequestBody ExExperimentMain exExperimentMain)
    {
        ExExperimentSide experimentSide = new ExExperimentSide();
        experimentSide.setMainTableId(exExperimentMain.getId());
        List<ExExperimentSide> exTemplateSides = exExperimentSideService.selectExExperimentSideList(experimentSide);
        int flag = 0;
        for (ExExperimentSide exTemplateSide : exTemplateSides) {
            if (exTemplateSide.getStepStatus().equals("1")){
                flag = 1;
            }
        }
        return AjaxResult.success(flag);
    }

    /**
     * 完成实验
     */
    @PostMapping("/compSy")
    public AjaxResult compSy(@RequestBody ExExperimentMain exExperimentMain)
    {
        ExExperimentMain experimentMain = exExperimentMainService.selectExExperimentMainById(exExperimentMain.getId());
        experimentMain.setExperimentStatus("2");
        Date date = new Date();
        experimentMain.setEndTime(date);
        experimentMain.setTimeDifference(timecha(experimentMain.getBeginTime(),date));
        return toAjax(exExperimentMainService.updateExExperimentMain(experimentMain));
    }

    public String timecha(Date date1,Date date2){
        LocalDateTime dateTime1 = date1.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        LocalDateTime dateTime2 = date2.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();

        Duration duration = Duration.between(dateTime1, dateTime2);
        long days = duration.toDays();
        long hours = duration.toHours();
        long minutes = duration.toMinutes();
        if (days == 0){
            if (hours == 0){
                return minutes + "分钟";
            }else {
                return hours + "小时";
            }
        }else {
            return days + "天";
        }

    }

    /**
     * 查询当前登陆用户
     */
    @GetMapping("/selectLoginUser")
    public AjaxResult selectLoginUser()
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = userService.selectUserById(loginUser.getUserId());
        return success(sysUser);
    }

    /**
     * 终止实验
     */
    @PostMapping("/shatDownSy")
    public AjaxResult shatDownSy(@RequestBody ExExperimentMain exExperimentMain)
    {
        ExExperimentMain experimentMain = exExperimentMainService.selectExExperimentMainById(exExperimentMain.getId());
        experimentMain.setExperimentStatus("3");
        experimentMain.setEndTime(new Date());
        return toAjax(exExperimentMainService.updateExExperimentMain(experimentMain));
    }

    /**
     * 修改学生实验主
     */
    @Log(title = "学生实验主表", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ExExperimentMain exExperimentMain)
    {
        //先删除字表
        ExExperimentSide exExperimentSide = new ExExperimentSide();
        exExperimentSide.setMainTableId(exExperimentMain.getId());
        List<ExExperimentSide> exExperimentSides = exExperimentSideService.selectExExperimentSideList(exExperimentSide);
        for (ExExperimentSide experimentSide : exExperimentSides) {
            exExperimentSideService.deleteExExperimentSideById(experimentSide.getId());
        }

        //再新增字表
        List<ExExperimentSide> sideTables = exExperimentMain.getSideTables();
        int index = 1;
        for (ExExperimentSide sideTable : sideTables) {
            sideTable.setMainTableId(exExperimentMain.getId());
            sideTable.setStepNum(String.valueOf(index));
            sideTable.setStepStatus("1");
            exExperimentSideService.insertExExperimentSide(sideTable);
            index++;
        }
        return toAjax(exExperimentMainService.updateExExperimentMain(exExperimentMain));
    }

    /**
     * 保存实验
     */
    @Log(title = "保存实验", businessType = BusinessType.UPDATE)
    @PutMapping("/saveSy")
    public AjaxResult saveSy(@RequestBody ExExperimentMain exExperimentMain)
    {
        //前台传过来的
        List<ExExperimentSide> sideTables = exExperimentMain.getSideTables();
        //后台查的
        ExExperimentMain experimentMain = exExperimentMainService.selectExExperimentMainById(exExperimentMain.getId());
        ExExperimentSide experimentSide = new ExExperimentSide();
        experimentSide.setMainTableId(experimentMain.getId());
        List<ExExperimentSide> exTemplateSides = exExperimentSideService.selectExExperimentSideList(experimentSide);
        //塞数据
        for (ExExperimentSide sideTable : sideTables) {
            for (ExExperimentSide exTemplateSide : exTemplateSides) {
                if (sideTable.getId().toString().equals(exTemplateSide.getId().toString())){
                    exTemplateSide.setStepSummary(sideTable.getStepSummary());
                    exTemplateSide.setPictureUrl(sideTable.getPictureUrl());
                    exExperimentSideService.updateExExperimentSide(exTemplateSide);
                }
            }
        }
        return toAjax(1);
    }

    /**
     * 开始计划
     */
    @Log(title = "学生开始实验", businessType = BusinessType.UPDATE)
    @GetMapping("/startLabor/{id}")
    public AjaxResult startLabor(@PathVariable String id)
    {
        ExExperimentMain experimentMain = exExperimentMainService.selectExExperimentMainById(id);
        experimentMain.setExperimentStatus("1");
        experimentMain.setBeginTime(new Date());
        return toAjax(exExperimentMainService.updateExExperimentMain(experimentMain));
    }

    /**
     * 删除学生实验主
     */
    @Log(title = "学生实验主表", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(exExperimentMainService.deleteExExperimentMainByIds(ids));
    }
}
